/*
** tp.c for  in /home/baraze_l/tek2/project/system_unix/my_ftp/TP
**
** Made by leo barazer
** Login   <baraze_l@epitech.net>
**
** Started on  Mon Apr  08 16:18:47 2013 leo barazer
** Last update Mon Apr  08 16:18:47 2013 leo barazer
*/

#include 	<sys/types.h>
#include 	<sys/socket.h>
#include 	<netdb.h>
#include 	<stdlib.h>
#include 	<netinet/in.h>
#include 	<arpa/inet.h>
#include 	<string.h>
#include 	<stdio.h>
#include 	<unistd.h>

int 		handle_client(const char *client_ip, int client_id)
{
	char 	buffer[2048];

	read(client_id, buffer, 2048);
	printf("From%s: %s\n", client_ip, buffer);
	return (1);
}

int 		main(int ac, char **av)
{
	int 				fd;
	int 				fd_client;
	struct sockaddr_in 	s_in_client;
	socklen_t 			s_in_len;
	struct protoent 	*pe;
	struct sockaddr_in 	s_addr;
	int 				port;
	char 				*client_ip;

	if (ac != 2)
		return (1);
	s_in_len = sizeof(struct sockaddr_in);
	port = atoi(av[1]);
	pe = getprotobyname("TCP");
	if (!pe)
		return (1);
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(port);
	s_addr.sin_addr.s_addr = INADDR_ANY;
	fd = socket(AF_INET, SOCK_STREAM, pe->p_proto);
	if (!fd)
		return (1);
	bind(fd, (const struct sockaddr *) &s_addr, sizeof(struct sockaddr_in));
	listen(fd, 42);
	fd_client = accept(fd, (struct sockaddr *)&s_in_client, &s_in_len);
	client_ip = inet_ntoa(s_in_client.sin_addr);
	printf("%s\n", client_ip);
	while(42)
		handle_client(client_ip, fd_client);
	close(fd);
	close(fd_client);
	return (0);
}
